package pl.edu.pw.mini.java2.Communicator.Client;

import java.net.*;
import java.io.*;

import static java.lang.System.out;

public class Client {
	/**
	 * TODO : dodac dokumentację.
	 */

	private DataOutputStream outToServer = null;
	private DataInputStream inFromServer = null;
	private Socket server = null;

	private WriterWorker writer;
	private ReaderWorker reader;

	private LoginInfo info;

	private ChatListener chatListener = null;
	private ClientListener clientsListener = null;

	public ClientListener getClientListener() {
		return clientsListener;
	}

	public void addClientListener(ClientListener contactsListener) {
		this.clientsListener = contactsListener;
		writer.sendMessage(new Message(Message.GET_AVAILABLE_CONTACT, ""
				.getBytes()));
	}

	public ChatListener getChatListener() {
		return chatListener;
	}
	
	public void addChatListener(ChatListener listener) {
		chatListener = listener;
	}	

	public LoginInfo getLoginInfo() {
		return info;
	}

	public void setLoginInfo(LoginInfo info) {
		this.info = info;
	}

	public Client() {
	}

	public Client(String login) {
		setLoginInfo(new LoginInfo(login));
	}

	public void ConnectToServer(String addr, int port) throws Exception {

		try {
			server = new Socket(addr, port);
			outToServer = new DataOutputStream(server.getOutputStream());
			inFromServer = new DataInputStream(server.getInputStream());
		} catch (Exception ex) {
			out.println("Can not connect with server!");
			throw ex;
		}
	}

	public void LogOnRequest() throws Exception {
		reader.setLastState(-1);
		if (info.getLogin().length() == 0)
			throw new Exception("Login failed");
		writer.sendMessage(new Message(Message.LOGIN_REQUEST, info.getLogin()
				.getBytes()));
		int state = -1;
		while ((state = reader.getLastState()) == -1)
			Thread.sleep(10);
		if (state == Message.ERROR)
			throw new Exception("Logon failed");
	}

	public void sendChatRequest(String name) throws Exception {
		reader.setLastState(-1);
		writer.sendMessage(new Message(Message.CHAT_REQUEST, name.getBytes()));
		int state = -1;
		while (state == -1) {
			state = reader.getLastState();
			Thread.sleep(10);
		}
		if (state == Message.ERROR)
			throw new Exception("Cannot get request");

	}

	public void sendChatRejectRequest() throws Exception {
		writer.sendMessage(new Message(Message.CHAT_REJECT, "".getBytes()));
	}

	public void sendChatTextMessage(String msg) {
		writer.sendMessage(new Message(Message.TEXT_MESSAGE, msg.getBytes()));		
	}

	public void sendChatVoiceMessage(byte[] msg) {
		writer.sendMessage(new Message(Message.VOICE_MESSAGE, msg));
	}

	public void start() {
		writer = new WriterWorker(outToServer);
		reader = new ReaderWorker(inFromServer, this);
		writer.start();
		reader.start();
	}

	public void close() {
		System.out.println("close() called");
		writer.close();
		reader.close();
		try {
			server.close();
		} catch (IOException e) {
		}
		writer = null;
		reader = null;
	}
}